package com.zyj.test.month1.day13;

import com.zyj.test.ListNode;

/**
 * @author Yijia Zhang
 * @create 2024-05-30 21:56
 */
public class code0025 {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode tmp = dummy;
        while (tmp != null) {
            tmp = swap(tmp, k);
        }
        return dummy.next;
    }

    //翻转 返回最后一个节点
    private ListNode swap(ListNode pre, int k) {
        ListNode tmp = pre;
        for (int i = 0; i < k; i++) {
            tmp = tmp.next;
            if (tmp == null) {
                return null;
            }
        }
        ListNode res = pre.next;
        //现在tmp是tail
        ListNode tail = tmp.next;
        tmp = pre.next;
        for (int i = 0; i < k; i++) {
            ListNode next = tmp.next;
            tmp.next = tail;
            tail = tmp;
            tmp = next;
            pre.next = tail;
        }
        return res;
    }

}
